package ViewFragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import JsonModel.FamiliarFriend;
import JsonModel.User;
import Net.JsonParse;
import Utilities.Configuration;
import adapter.AdapterAcceptFriend;
import adapter.AdapterAcceptFriend.Adapter;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import animationmenu.CollapseAnimation;
import animationmenu.CollapseAnimationForView;
import animationmenu.ExpandAnimation;
import animationmenu.ExpandAnimationForView;

import com.actionbarsherlock.app.SherlockFragment;
import com.adgroup.smartnote.AcceptActivity;
import com.adgroup.smartnote.AddMemberToGroupActivity;
import com.adgroup.smartnote.R;
import com.adgroup.smartnote.RegisterActivity;
import com.adgroup.smartnote.SmartNoteActivity;
import com.fortysevendeg.swipelistview.BaseSwipeListViewListener;
import com.fortysevendeg.swipelistview.SwipeListView;

import database.Database;

public class AcceptFriendActivity extends SherlockFragment{

	ListView lv;
	static AdapterAcceptFriend.Adapter adapAccept;
	User u;
	ProgressBar progress;
	TextView tv;
	private boolean isExpanded;
	static ArrayList<User> arrs = new ArrayList<User>();
	int LAST_POSITION = -1;
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.acceptfriend, container, false);
	}
	@SuppressLint({ "InlinedApi", "NewApi" })
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		Log.d("log", "oncrea te asd");
		lv = (ListView) getView().findViewById(R.id.listViewAcceptFriend);
		progress = (ProgressBar) getView().findViewById(R.id.progressBarAcceptFriend);
		tv = (TextView) getView().findViewById(R.id.textViewAcceptFriend);
		
		lv.setFastScrollEnabled(true);
		lv.setScrollingCacheEnabled(true);
		
		//get list request
		u = new Database(AcceptFriendActivity.this.getSherlockActivity()).getUser();
		if(u!=null){
			new AsynSendRequest().execute(new String[]{u.getUserId()});
		}
		//
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				((AcceptActivity)AcceptFriendActivity.this.getSherlockActivity()).ShowSlidingMenu(arrs.get(arg2));
			}
		});
	} 
	public void updateAnimationItem(int position) {
		if(position!=LAST_POSITION){			
			View v = lv.getChildAt(position - lv.getFirstVisiblePosition()).findViewById(R.id.front);			
			new ExpandAnimationForView(v, (int)(Configuration.screenWidth*0.5),
					Animation.RELATIVE_TO_SELF, 0.0f,
					Animation.RELATIVE_TO_SELF, -0.5f, 0, 0.0f, 0, 0.0f);
			v.setTag("true"); //expand
			if(LAST_POSITION!=-1){
				View v1 = lv.getChildAt(LAST_POSITION - lv.getFirstVisiblePosition()).findViewById(R.id.front);
				if(v1.getTag()!=null && v1.getTag().toString().equalsIgnoreCase("true")){
					new CollapseAnimationForView(v1, (int)(Configuration.screenWidth*0.5),
							Animation.RELATIVE_TO_SELF, -0.5f,
							Animation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0, 0.0f);
					v1.setTag("false");
				}
			}
			LAST_POSITION = position;
		}
		else{
			View v = lv.getChildAt(position - lv.getFirstVisiblePosition()).findViewById(R.id.front);
			if(v.getTag()!=null && v.getTag().toString().equalsIgnoreCase("true")){
				new CollapseAnimationForView(v, (int)(Configuration.screenWidth*0.5),
					Animation.RELATIVE_TO_SELF, -0.5f,
					Animation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0, 0.0f);
				v.setTag("false");
			}
			else{
				new ExpandAnimationForView(v, (int)(Configuration.screenWidth*0.5),
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, -0.5f, 0, 0.0f, 0, 0.0f);
					v.setTag("true");
			}
		}
	}
	
	public int convertDpToPixel(float dp) {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return (int) px;
    }
	public void updateListUser(User u){
		arrs.remove(u);
		adapAccept.notifyDataSetChanged();
	}
	//is accept request make friend
	public class AsynAcceptRequest extends AsyncTask<String, Void, String>
	{				
		private ProgressDialog process;
		int accept;
		User u;
		String parent;
		Context c;
		public AsynAcceptRequest(int accept, User u, String string, Context acceptActivity){
			this.accept = accept;
			this.u = u;
			this.parent = string;
			c = acceptActivity;
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();			
				if(accept==1){
					process = ProgressDialog.show(c,"",c.getResources().getString(R.string.process_acccept_make_friend), true);
				}
				else{
					process = ProgressDialog.show(c, "",
							c.getResources().getString(R.string.process_deny_make_friend), true);
				}			
		}
		@Override
		protected String doInBackground(String... params) {			
			return new JsonParse().sendRequestAcceptFriendList(AcceptFriendActivity.this.getSherlockActivity(), params[0], params[1]);
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Configuration.result);
				if(r.equalsIgnoreCase("0")){
					Toast.makeText(c, c.getResources().getString(R.string.toast_deny_make_friend)+" "+u.getNickName(), Toast.LENGTH_LONG).show();
				}
				else{
					Toast.makeText(c, u.getNickName() +" " +c.getResources().getString(R.string.toast_accept_make_friend), Toast.LENGTH_LONG).show();
				}
					
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			process.dismiss();
			adapAccept.removeUser(this.u);
			LAST_POSITION = -1;
			if(parent.equalsIgnoreCase("parent")){
				((AcceptActivity)c).hideSlidingMenu();
			}
			super.onPostExecute(result);
		}		
	}
	//set request make friend
	class AsynSendRequest extends AsyncTask<String, Void, String>
	{				
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress.setVisibility(View.VISIBLE);
			lv.setVisibility(View.GONE);
			tv.setVisibility(View.GONE);
			if(arrs!=null){
				arrs.clear();
			}
		}
		@Override
		protected String doInBackground(String... params) {			
			return new JsonParse().getListAcceptMakeFriend(AcceptFriendActivity.this.getSherlockActivity(), params);
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Configuration.result);
				if(!r.equalsIgnoreCase("norow")){
					JSONArray arr = json.getJSONArray(Configuration.result);
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String requestId = obj.getString(User.keyRequestId);
						String userId = obj.getString(User.keyUserId);
						String birthday = obj.getString(User.keyBirthday);
						String nickName = obj.getString(User.keyNickName);
						String gender = obj.getString(User.keyGender);
						String gmail = obj.getString(User.keyGmail);
						String link = obj.getString(User.keyLink);
						String time = obj.getString(User.keyTime);
						User u = new User(userId, nickName, gender, birthday, link, gmail, time, requestId);
						arrs.add(u);
					}
					adapAccept = new AdapterAcceptFriend(AcceptFriendActivity.this, arrs).new Adapter();
					lv.setAdapter(adapAccept);
					tv.setVisibility(View.GONE);
					lv.setVisibility(View.VISIBLE);
				}
				else{
					tv.setVisibility(View.VISIBLE);
					lv.setVisibility(View.GONE);
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			progress.setVisibility(View.GONE);
			
			super.onPostExecute(result);
		}		
	}
	public void sendRequestAcceptMakeFriend(User user, int i, String string, Context acceptActivity) {
		new AsynAcceptRequest(i,user,string,acceptActivity).execute(new String[]{user.getRequestId(),i+""});
	}
}
